package day7.problem3;

import java.util.*;

//岛屿数量
//https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e?tpId=196&tqId=37167&ru=/exam/oj


public class Solution {
    int n, m;
    boolean[][] st;
    public int solve (char[][] grid) {
        int ret = 0;
        n = grid.length; m = grid[0].length;
        st = new boolean[n][m];
        for(int i = 0; i<n; i++) {
            for(int j = 0; j<m; j++) {
                if(grid[i][j] == '1' && !st[i][j]) {
                    st[i][j] = true;
                    ret++;
                    dfs(grid, i, j);
                }
            }
        }
        return ret;
    }
    int[] xx = {1, -1, 0, 0};
    int[] yy = {0, 0, 1, -1};
    private void dfs(char[][] grid, int x, int y) {
        for(int i = 0; i<4; i++) {
            int dx = x + xx[i], dy = y + yy[i];
            if(dx >= 0 && dx < n && dy >= 0 && dy < m && grid[dx][dy] == '1' && !st[dx][dy]) {
                st[dx][dy] = true;
                dfs(grid, dx, dy);
            }
        }
    }
}